<template>
	<!-- 商品佣金组件 -->
	<div class="radio-top-bar">
		<el-form :model="form" label-width="130px" ref="form" :rules="rules" style="margin-top: -12px;">
      <el-form-item label="商品佣金" class="one-label">
        <el-form-item label="佣金设置：" label-width="170px" prop="totalRadio">
          <!-- 校验用 -->
          <el-input v-show="false" v-model="totalRadio"></el-input>
          <div class="tips blue">
            <p>1、实际佣金以比例乘以零售价来计算。</p>
            <p>2、比例和实际佣金将保留小数点后俩位并四舍五入。</p>
            <p>3、若商品为淘宝联盟商品，则提成及佣金是以商品利润（零售价减去供应价后的金额）为基数再按比例计算佣金。</p>
          </div>
          <el-row :gutter="20" class="mar-t-20">
            <el-col :md="24" :lg="12">
              <div class="border-d7">
                <h3 class="gray-t-bar font-normal font-14 text-align-c mar-b-18">主播佣金设置</h3>

                <template v-if="enterpriseConfig.patternCommissionType == 2">
                  <el-form-item label="一级合伙人：" label-width="130px">
                    <div class="flex v-align-c">
                      <el-input v-model="form.anchorLevelOnePartnerRatio" 
                        @keyup.native="form.anchorLevelOnePartnerRatio = checkInputNum(form.anchorLevelOnePartnerRatio)"
                        class="width-per-35">
                        <template slot="append">%</template>
                      </el-input>
                      <div class="pad-l-10 height-40 mar-t--16">
                        <div class="line-h-unset height-20 mar-b-1">
                          <span>实际佣金：</span>
                          <span class="font-orange-2 font-w line-h-unset">￥{{ anchorLevelOnePartnerCommission }}</span>
                        </div>
                        <div class="line-h-unset height-20">
                          <span class="font-blue-2 font-under cursor-p line-h-unset" @click="handlePartnerGrade(1,1)">设置等级佣金</span>
                          <span class="font-color-9 line-h-unset">{{ form.anchorOnePartnerGradeAuth == 1 ? '（已开启）' : '（已关闭）' }}</span>
                        </div>
                      </div>
                    </div>
                    <p class="font-12 font-color-9 mar-0">一级合伙人自己招募或下架合伙人/招募员招募的主播产生的商品返佣</p>
                  </el-form-item>

                  <el-form-item label="二级合伙人：" label-width="130px">
                    <div class="flex v-align-c">
                      <el-input v-model="form.anchorLevelTwoPartnerRatio" 
                        @keyup.native="form.anchorLevelTwoPartnerRatio = checkInputNum(form.anchorLevelTwoPartnerRatio)"
                        class="width-per-35">
                        <template slot="append">%</template>
                      </el-input>
                      <div class="pad-l-10">
                        <span>实际佣金：</span>
                        <span class="font-orange-2 font-w">￥{{ anchorLevelTwoPartnerCommission }}</span>
                      </div>
                    </div>
                    <p class="font-12 font-color-9 mar-0">二级合伙人自己招募或下架招募员招募的主播产生的商品返佣</p>
                  </el-form-item>
                </template>

                <template v-if="enterpriseConfig.recruiterCommissionType == 2">
                  <el-form-item label="招募员：" label-width="130px">
                    <div class="flex v-align-c">
                      <el-input v-model="form.anchorRecruiterRatio" 
                        @keyup.native="form.anchorRecruiterRatio = checkInputNum(form.anchorRecruiterRatio)"
                        class="width-per-35">
                        <template slot="append">%</template>
                      </el-input>
                      <div class="pad-l-10">
                        <span>实际佣金：</span>
                        <span class="font-orange-2 font-w">￥{{ anchorRecruiterCommission }}</span>
                      </div>
                    </div>
                    <p class="font-12 font-color-9 mar-0">招募员自己招募的主播产生的商品返佣</p>
                  </el-form-item>
                </template>

                <el-form-item label="店铺主播：" label-width="130px">
                  <div class="flex v-align-c">
                    <el-input v-model="form.anchorRatio"
                      @keyup.native="form.anchorRatio = checkInputNum(form.anchorRatio)" 
                      class="width-per-35">
                      <template slot="append">%</template>
                    </el-input>
                    <div class="pad-l-10">
                      <span>实际佣金：</span>
                      <span class="font-orange-2 font-w">￥{{ anchorCommission }}</span>
                    </div>
                  </div>
                  <p class="font-12 font-color-9 mar-0">主播在私域微信小程序端带货后获得的佣金</p>
                </el-form-item>

                <el-form-item label="平台主播：" label-width="130px">
                  <div class="flex v-align-c">
                    <el-input v-model="form.anchorThirdPlatformRatio" 
                      @keyup.native="form.anchorThirdPlatformRatio = checkInputNum(form.anchorThirdPlatformRatio)" 
                      class="width-per-35">
                      <template slot="append">%</template>
                    </el-input>
                    <div class="pad-l-10">
                      <span>实际佣金：</span>
                      <span class="font-orange-2 font-w">￥{{ anchorThirdPlatformCommission }}</span>
                    </div>
                  </div>
                  <p class="font-12 font-color-9 mar-0">主播在公域抖音/快手等平台带货后获得的佣金</p>
                </el-form-item>
              </div>
            </el-col>

            <el-col :md="24" :lg="12">
              <div class="border-d7">
                <h3 class="gray-t-bar font-normal font-14 text-align-c mar-b-18">小B佣金设置</h3>

                <template v-if="enterpriseConfig.patternCommissionType == 2">
                  <el-form-item label="一级合伙人：" label-width="130px">
                    <div class="flex v-align-c">
                      <el-input v-model="form.levelOnePartnerRatio" 
                        @keyup.native="form.levelOnePartnerRatio = checkInputNum(form.levelOnePartnerRatio)" 
                        class="width-per-35">
                        <template slot="append">%</template>
                      </el-input>
                      <div class="pad-l-10">
                        <span>实际佣金：</span>
                        <span class="font-orange-2 font-w">￥{{ levelOnePartnerCommission }}</span>
                      </div>
                    </div>
                    <p class="font-12 font-color-9 mar-0">一级合伙人自己招募或下架合伙人/招募员招募的店主产生的商品返佣</p>
                  </el-form-item>

                  <el-form-item label="二级合伙人：" label-width="130px">
                    <div class="flex v-align-c">
                      <el-input v-model="form.levelTwoPartnerRatio" 
                        @keyup.native="form.levelTwoPartnerRatio = checkInputNum(form.levelTwoPartnerRatio)" 
                        class="width-per-35">
                        <template slot="append">%</template>
                      </el-input>
                      <div class="pad-l-10">
                        <span>实际佣金：</span>
                        <span class="font-orange-2 font-w">￥{{ levelTwoPartnerCommission }}</span>
                      </div>
                    </div>
                    <p class="font-12 font-color-9 mar-0">二级合伙人自己招募或下架招募员招募的店主产生的商品返佣</p>
                  </el-form-item>
                </template>

                <template v-if="enterpriseConfig.recruiterCommissionType == 2">
                  <el-form-item label="招募员：" label-width="130px">
                    <div class="flex v-align-c">
                      <el-input v-model="form.recruiterRatio" 
                        @keyup.native="form.recruiterRatio = checkInputNum(form.recruiterRatio)" 
                        class="width-per-35">
                        <template slot="append">%</template>
                      </el-input>
                      <div class="pad-l-10">
                        <span>实际佣金：</span>
                        <span class="font-orange-2 font-w">￥{{ recruiterCommission }}</span>
                      </div>
                    </div>
                    <p class="font-12 font-color-9 mar-0">招募员自己招募的店主产生的商品返佣</p>
                  </el-form-item>
                </template>

                <el-form-item label="店主：" label-width="130px">
                  <div class="flex v-align-c">
                    <el-input v-model="form.distributeRatio" 
                      @keyup.native="form.distributeRatio = checkInputNum(form.distributeRatio)" 
                      class="width-per-35">
                      <template slot="append">%</template>
                    </el-input>
                    <div class="pad-l-10 height-40 mar-t--16">
                      <div class="line-h-unset height-20 mar-b-1">
                        <span>实际佣金：</span>
                        <span class="font-orange-2 font-w line-h-unset">￥{{ distributeCommission }}</span>
                      </div>
                      <div class="line-h-unset height-20">
                        <span class="font-blue-2 font-under cursor-p line-h-unset" @click="doSetGrade">设置等级佣金</span>
                        <span class="font-color-9 line-h-unset">{{ form.memberGradeAuth == 1 ? '（已开启）' : '（已关闭）' }}</span>
                      </div>
                    </div>
                  </div>
                  <p class="font-12 font-color-9 mar-0">店主的店铺卖出该商品后获得的佣金</p>
                </el-form-item>

                <el-form-item label="顾客分销商：" label-width="130px">
                  <div class="flex v-align-c">
                    <el-input v-model="form.shareMemberRatio" 
                      @keyup.native="form.shareMemberRatio = checkInputNum(form.shareMemberRatio)" 
                      class="width-per-35">
                      <template slot="append">%</template>
                    </el-input>
                    <div class="pad-l-10">
                      <span>实际佣金：</span>
                      <span class="font-orange-2 font-w">￥{{ shareMemberCommission }}</span>
                    </div>
                  </div>
                  <p class="font-12 font-color-9 mar-0">顾客分销该商品后获得的返佣</p>
                </el-form-item>
              </div>
            </el-col>
          </el-row>
        </el-form-item>

      </el-form-item>
		</el-form>

    <!-- 店主等级佣金 -->
    <el-dialog title="设置店主等级佣金" :visible.sync="shopGradeForm.gradeVisible" :close-on-press-escape="true" width="500px">
      <div class="pad-b-10">
        <el-switch class="pad-l-10" v-model="shopGradeForm.gradeFlage" active-color="#13ce66" inactive-color="#ff4949"></el-switch>
        <span class="mar-l-5">{{ shopGradeForm.gradeFlage ? '启用' : '禁用' }}店主佣金等级</span>
        <el-button type="text" class="pad-l-30" @click="doCopyCommission">复制等级默认佣金比例</el-button>
      </div>
      <div class="pad-l-10 pad-r-10">
        <el-table :data="shopGradeForm.gradeList">
          <el-table-column prop="gradeName" label="店主等级"></el-table-column>
          <el-table-column label="佣金" align="center">
            <template slot-scope="scope">
              <el-input v-model="scope.row.commissionRate" 
                @keyup.native="scope.row.commissionRate = checkInputNum(scope.row.commissionRate)" 
                placeholder="请输入佣金">
                <template slot="append">%</template>
              </el-input>
            </template>
          </el-table-column>
        </el-table>
        <p class="font-12 font-color-9 mar-0">请输入小于100数字，不填则默认为0</p>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="doSaveGrade">确定</el-button>
        <el-button @click="shopGradeForm.gradeVisible = false">取消</el-button>
      </div>
    </el-dialog>

    <!-- 设置合伙人佣金组件 -->
    <partner-grade-commission ref="partnerGradeCommissionRef" :onSuccess="handlePartnerGradeCommissionSuccess"></partner-grade-commission>
      
	</div>
</template>

<script>
  import { listGoodsGrade } from '@/api/goods/goodsMemberGrade'

  import goodsBus from '@/views/goods/edit/goods-bus'

  import PartnerGradeCommission from './components/partner-grade-commission/index'
  
  export default {
    mixins: [goodsBus],
    props: {
      // 跳转源 30：零售 31：批发
      fromListPage: {
        type: Number,
        default: 30
      },
      // 商品对象
      goodsObj: {
        type: Object
      }
    },
    components: {
      PartnerGradeCommission
    },
    computed: {
      // 总比例
      totalRadio() {
        const totalRadio = this.parseRadio(this.form.anchorLevelOnePartnerRatio) +
                           this.parseRadio(this.form.anchorLevelTwoPartnerRatio) +
                           this.parseRadio(this.form.anchorRecruiterRatio) +
                           this.parseRadio(this.form.anchorRatio) +
                           this.parseRadio(this.form.anchorThirdPlatformRatio) +
                           this.parseRadio(this.form.levelOnePartnerRatio) +
                           this.parseRadio(this.form.levelTwoPartnerRatio) +
                           this.parseRadio(this.form.recruiterRatio) +
                           this.parseRadio(this.form.distributeRatio) +
                           this.parseRadio(this.form.shareMemberRatio)
        return totalRadio * 100
      },
      // 主播所属一级合伙人佣金
      anchorLevelOnePartnerCommission() {
        return this.calcCommission(this.form.anchorLevelOnePartnerRatio)
      },
      // 主播所属二级合伙人佣金
      anchorLevelTwoPartnerCommission() {
        return this.calcCommission(this.form.anchorLevelTwoPartnerRatio)
      },
      // 主播所属招募员佣金
      anchorRecruiterCommission() {
        return this.calcCommission(this.form.anchorRecruiterRatio)
      },
      // 店铺主播佣金
      anchorCommission() {
        return this.calcCommission(this.form.anchorRatio)
      },
      // 平台主播佣金
      anchorThirdPlatformCommission() {
        return this.calcCommission(this.form.anchorThirdPlatformRatio)
      },
      // 一级合伙人佣金
      levelOnePartnerCommission() {
        return this.calcCommission(this.form.levelOnePartnerRatio)
      },
      // 二级合伙人佣金
      levelTwoPartnerCommission() {
        return this.calcCommission(this.form.levelTwoPartnerRatio)
      },
      // 招募员佣金
      recruiterCommission() {
        return this.calcCommission(this.form.recruiterRatio)
      },
      // 店主佣金
      distributeCommission() {
        return this.calcCommission(this.form.distributeRatio)
      },
      // 分销商佣金
      shareMemberCommission() {
        return this.calcCommission(this.form.shareMemberRatio)
      }
    },
    data() {
      // 总比例规则
      const totalRadioRule = (rule, value, callback) => {
        if (this.form.anchorOnePartnerGradeAuth === 1) {
          if (this.form.partnerGradeCommissionList && this.form.partnerGradeCommissionList.length > 0) {
            var partnerGradeCommissionList = this.form.partnerGradeCommissionList.filter(function(item) {
              if (item.partnerType === 1 && item.commissionType === 1) {
                return item
              }
            })
            var totalRadio = this.totalRadio - this.parseRadio(this.form.anchorLevelOnePartnerRatio)
            for (var i = 0; i < partnerGradeCommissionList.length; i++) {
              const resTotalRadio = totalRadio + parseFloat(partnerGradeCommissionList[i].commissionRate)
              if (resTotalRadio > 100) {
                return callback(new Error('佣金比例总和不能超过100'))
              }
            }
          }
        }
        if (this.totalRadio > 100) {
          return callback(new Error('佣金比例总和不能超过100'))
        }
        callback()
      }
      return {
        // 零售价
        goodsPrice: 0,
        tempIndex: 0,
        // 表单
        form: {
          goodsId: '',
          anchorLevelOnePartnerRatio: 0,
          anchorLevelTwoPartnerRatio: 0,
          anchorRecruiterRatio: 0,
          anchorRatio: 0,
          anchorThirdPlatformRatio: 0,
          levelOnePartnerRatio: 0,
          levelTwoPartnerRatio: 0,
          recruiterRatio: 0,
          distributeRatio: 0,
          shareMemberRatio: 0,
          memberGradeAuth: 0,
          gradeList: [],
          anchorOnePartnerGradeAuth: 0,
          partnerGradeCommissionList: []
        },
        // 表单规则
        rules: {
          totalRadio: [
            { trigger: 'change', validator: totalRadioRule }
          ]
        },
        // 企业配置
        enterpriseConfig: {
          // 合伙人提成比例取用规则 1:按合伙人 2：按商品
          patternCommissionType: 1,
          // 招募员提成比例取用规则 1:按招募员 2：按商品
          recruiterCommissionType: 1
        },
        // 店主等级表单
        shopGradeForm: {
          gradeFlage: false,
          gradeVisible: false,
          gradeList: []
        }
      }
    },
    created() {
    },
    mounted() {
      const goodsBaseData = this.$store.state.goodsBaseData
      Object.assign(this.enterpriseConfig, goodsBaseData.enterpriseConfig)
      this.initForm()
      const that = this
      // 监听事件
      that.bindChangeSellPrice(function(value) {
        that.goodsPrice = value
      })
    },
    methods: {
      // 初始化表单
      initForm() {
        if (this.goodsObj.goodsId) {
          Object.assign(this.form, this.goodsObj)
        }
      },
      // 转换格式
      parseRadio(radio) {
        const radioParse = parseFloat(radio)
        const finalRadio = isNaN(radioParse) ? 0 : radioParse / 100
        return finalRadio
      },
      // 计算佣金
      calcCommission(radio) {
        const finalRadio = this.parseRadio(radio)
        return (this.goodsPrice * finalRadio).toFixed(2)
      },
      // 设置店主等级佣金事件
      doSetGrade() {
        this.shopGradeForm.gradeFlage = this.form.memberGradeAuth === 1
        if (this.shopGradeForm.gradeList.length === 0) {
          listGoodsGrade(this.getEnterpriseId(), this.form.goodsId, '').then(response => {
            if (response.isError) return
            response.data.forEach(item => {
              const obj = {
                memberGradeId: item.memberGradeId,
                defaultCommissionRate: item.defaultCommissionRate,
                gradeName: item.gradeName,
                commissionRate: item.commissionRate
              }
              this.shopGradeForm.gradeList.push(obj)
            })
            this.shopGradeForm.gradeVisible = true
          })
        } else {
          this.shopGradeForm.gradeVisible = true
        }
      },
      // 保存等级
      doSaveGrade() {
        const errorCount = this.shopGradeForm.gradeList.filter(item => this.parseRadio(item.commissionRate) > 1).length
        if (errorCount > 0) {
          this.$message({ message: '佣金比例不能超过100', type: 'error' })
          return
        }
        this.form.memberGradeAuth = this.shopGradeForm.gradeFlage ? 1 : 0
        this.form.gradeList = this.shopGradeForm.gradeList
        this.shopGradeForm.gradeVisible = false
      },
      // 复制等级默认佣金比例事件
      doCopyCommission() {
        this.shopGradeForm.gradeList.forEach(item => {
          this.$set(item, 'commissionRate', item.defaultCommissionRate)
        })
      },
      // 设置合伙人等级佣金
      // commissionType:佣金类型，1-主播，2-小b
      handlePartnerGrade(commissionType, partnerGradeType) {
        this.$refs.partnerGradeCommissionRef.open(this.form.goodsId, commissionType, partnerGradeType, this.form.anchorOnePartnerGradeAuth)
      },
      handlePartnerGradeCommissionSuccess(partnerGradeAuth, partnerType, commissionType, dataList) {
        this.form.anchorOnePartnerGradeAuth = partnerGradeAuth
        this.form.partnerGradeCommissionList = dataList
        let partnerGradeCommissionList = this.form.partnerGradeCommissionList
        if (partnerGradeCommissionList && partnerGradeCommissionList.length > 0) {
          partnerGradeCommissionList = partnerGradeCommissionList.filter(function(item) {
            if (item.partnerType !== partnerType && item.commissionType !== commissionType) {
              return item
            }
          })
          partnerGradeCommissionList = partnerGradeCommissionList.concat(dataList)
        } else {
          partnerGradeCommissionList = []
          partnerGradeCommissionList = partnerGradeCommissionList.concat(dataList)
        }
        this.$set(this.form, 'partnerGradeCommissionList', partnerGradeCommissionList)
        if (partnerGradeAuth === 1) {
          this.checkForm(['totalRadio'])
        }
      },
      // 表单校验 true：成功 false：失败
      checkForm(prop) {
        let ret = true
        if (prop) {
          const checkArrays = Array.isArray(prop) ? prop : [prop]
          this.$refs['form'].validateField(checkArrays, (valid, result) => {
            if (valid) {
              const propKeys = Object.keys(result)
              this.$refs['form'].fields.forEach(field => {
                const index = propKeys.indexOf(field.prop)
                if (index !== -1) {
                  this.$emit('addVaildShow', field)
                }
              })
              ret = false
            }
          })
        } else {
          this.$refs['form'].validate((valid, result) => {
            if (!valid) {
              const propKeys = Object.keys(result)
              this.$refs['form'].fields.forEach(field => {
                const index = propKeys.indexOf(field.prop)
                if (index !== -1) {
                  this.$emit('addVaildShow', field)
                }
              })
              ret = false
            }
          })
        }
        return ret
      },
      // 提交表单
      submitForm() {
        const submitForm = {
          distributeRatio: this.form.distributeRatio, // 分销提成比例
          recruiterRatio: this.form.recruiterRatio, // 招募员提成比例
          shareMemberRatio: this.form.shareMemberRatio, // 顾客分销佣金比例
          levelOnePartnerRatio: this.form.levelOnePartnerRatio, // 一级合伙人提成比例
          levelTwoPartnerRatio: this.form.levelTwoPartnerRatio, // 二级合伙人提成比例
          anchorRatio: this.form.anchorRatio, // 主播推广比例
          anchorLevelOnePartnerRatio: this.form.anchorLevelOnePartnerRatio, // 主播所属一级合伙人佣金比例
          anchorLevelTwoPartnerRatio: this.form.anchorLevelTwoPartnerRatio, // 主播所属二级合伙人佣金比例
          anchorRecruiterRatio: this.form.anchorRecruiterRatio, // 主播所属招募员佣金比例
          anchorThirdPlatformRatio: this.form.anchorThirdPlatformRatio, // 第三方平台主播的佣金比例
          gradeList: this.form.gradeList, // 店主等级集合
          memberGradeAuth: this.form.memberGradeAuth, // 店主等级佣金权限 0关闭 1开启
          partnerGradeCommissionList: this.form.partnerGradeCommissionList, // 主播合伙人等级佣金集合
          anchorOnePartnerGradeAuth: this.form.anchorOnePartnerGradeAuth // 主播合伙人等级佣金权限 0关闭 1开启
        }
        return submitForm
      }
    }
  }
</script>

<style lang="less" scoped>
  .border-d7 {
    /deep/ .el-input__inner {
      padding: 0;
      padding-left: 10px;
    }
  }
  .radio-top-bar {
    /deep/ .el-input-group__append,
    .el-input-group__prepend {
      padding: 0 10px;
    }
  }
</style>
